package com.lagou.filter;

import com.lagou.feign.TokenFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {


    @Autowired
    private TokenFeign tokenFeign;

    /**
     *、
     * 统⼀一认证（登录时验证⽤用户名密码是否合法，合法调⽤用⽤用户微服务⽣生成token，写⼊入cookie，并且携带邮箱地址重定向到欢迎⻚页⾯面；
     * 后续请求再到来时，验证客户端请求cookie中携带的token是否合法，
     * 合法则放⾏行行，此处不不考虑token更更新问题
     * @param exchange
     * @param chain
     * @return
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("LoginFilter begin");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取uri
        String uri = request.getURI().getPath();
        //2.对用户微服务和验证码微服务的请求不过滤
        log.info("uri:" + uri);
        if(uri.contains("user")){
            log.info("LoginFilter 放行");
            return chain.filter(exchange);
        }
        if(uri.contains("code")){
            log.info("LoginFilter 放行");
            return chain.filter(exchange);
        }
        //3.对其他请求进行token合法性判断
        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst("token");
        if(httpCookie == null){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            return exchange.getResponse().setComplete();
        }
        String cookieValue = httpCookie.getValue();
        if(StringUtils.isEmpty(cookieValue)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            return exchange.getResponse().setComplete();
        }
        String email = tokenFeign.checkToken(cookieValue);
        if(StringUtils.isEmpty(email)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            return exchange.getResponse().setComplete();
        }
        log.info("LoginFilter 放行");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

